package com.romotc.qqrobot.webqq.bean;

import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang.StringUtils;
import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.JsonToken;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.sym.Name;

import com.romotc.qqrobot.bean.QQLogedin;

/**
 * 发送消息接口 请求对象 请求体部分的内容
 * @author Administrator
com.romotc.qqrobot.webqq.qqInterfaceCatching.Send_buddy_msg2_Msg_id_Catching

r=
{
	"to":953863072,
	"face":540,
	"content":
			"[
				 \"dda\",
				 [\"font\",
				 	{\"name\":\"宋体\",\"size\":\"10\",\"style\":[0,0,0],\"color\":\"000000\"}
				 ]
			 ]",
	"msg_id":74520004,
	"clientid":"53452869",
	"psessionid":"8368046764001d636f6e6e7365727665725f77656271714031302e3133342e362e31333800001950000011e1036e0400d8e8885e6d0000000a403562426a684e7a484c6d00000028b999bb75a0eb45fab0153148463ddc30283298699d9a7f963d2b39cfff4d5caef13527ad266fcb02"
}
&clientid=53452869
&psessionid=8368046764001d636f6e6e7365727665725f77656271714031302e3133342e362e31333800001950000011e1036e0400d8e8885e6d0000000a403562426a684e7a484c6d00000028b999bb75a0eb45fab0153148463ddc30283298699d9a7f963d2b39cfff4d5caef13527ad266fcb02

 */
public class Send_buddy_msg2_RequestBody {

	private long to;
	private int face;
	private String msgContext_data;
	private String msgContext_font_name;
	private String msgContext_font_size;
	private int[] msgContext_font_style;
	private String msgContext_font_color;
	
	private int msgId;
	private int clientId;
	private String psessionid;
	
	public Send_buddy_msg2_RequestBody() {
		
	}
	
	public Send_buddy_msg2_RequestBody(long sendToUin, String msgStr, QQLogedin senderQQ) {
		this.to = sendToUin;
		this.msgContext_data = msgStr;
		
		//发送者的QQ信息
		this.msgId = senderQQ.getMsg_id(); //这里设置不准确 在发送队列中设置
		this.clientId = senderQQ.getClientId();
		this.psessionid = senderQQ.getPsessionid();
		this.face = 540;
		
		
		//默认设置
		this.msgContext_font_color = "339966";
		this.msgContext_font_name = "宋体";
		this.msgContext_font_size = "13";
		this.msgContext_font_style = new int[]{0,0,0};
		
	}
	
	
	/**
	 * 从请求总解析所发出的信息对象
	 * @param rqSpy
	 * @return
	 */
	public static Send_buddy_msg2_RequestBody parseFromRequestBody(String msgStr) throws Exception{
		if(StringUtils.isBlank(msgStr)) 
			return null;
		
		//去掉第一个{之前的
		int idx = msgStr.indexOf("{");
		if(idx == -1) 
			return null;
		msgStr = msgStr.substring(idx);
		
		//将最后一个}后面的内容去掉
		idx = msgStr.lastIndexOf("}");
		
		if(idx == -1) 
			return null;
		
		msgStr = msgStr.substring(0, idx + 1);
		
		return parseFromJsonStr(msgStr);
	}
	
	
	/**
	 * 将Bean解析为腾讯接口需要的格式
	 */
	@Override
	public String toString() {
		/**
r:{"to":3935323488,"face":540,"content":"[\"ddda\",[\"font\",{\"name\":\"宋体\",\"size\":\"13\",\"style\":[0,0,0],\"color\":\"339966\"}]]","msg_id":56600006,"clientid":"68660513","psessionid":"8368046764001d636f6e6e7365727665725f77656271714031302e3133342e362e313338000076ce00001246036e0400d8e8885e6d0000000a40765735757a39446f4d6d00000028af926e1ece1fe6022dca52aa7125f4d7b5b0f7795c25aab78700cd93d65410088f7db7e04d3e07af"}
clientid:68660513
psessionid:8368046764001d636f6e6e7365727665725f77656271714031302e3133342e362e313338000076ce00001246036e0400d8e8885e6d0000000a40765735757a39446f4d6d00000028af926e1ece1fe6022dca52aa7125f4d7b5b0f7795c25aab78700cd93d65410088f7db7e04d3e07af
		 */
		StringBuilder bld = new StringBuilder();
		          //r:{"to  ":          3935323488       ,
		bld.append("r={\"to\":").append(this.to).append(",");
		//           "face ":          540                ,
		bld.append("\"face\":").append(this.face).append(",");
		//           "content ": "[\  "          ddda                           \ ",
		bld.append("\"content\":\"[\\\"").append(this.msgContext_data).append("\\\",");
		//          [\  "font \ ",           { \ "name \ ":            \ "          宋体                                        \  ",
		bld.append("[\\\"font\\\",").append("{\\\"name\\\":").append("\\\"").append(this.msgContext_font_name).append("\\\",");
		//           \ "size \ ": \ "          13                                  \ ",
		bld.append("\\\"size\\\":\\\"").append(this.msgContext_font_size).append("\\\",");
		//           \ "style \ ":[0,0,0],
		bld.append("\\\"style\\\":[")
			.append(this.msgContext_font_style[0]).append(",")
			.append(this.msgContext_font_style[1]).append(",")
			.append(this.msgContext_font_style[2]).append("],");
		//           \ "color \ ": \ "          339966                               \ "}]] ",
		bld.append("\\\"color\\\":\\\"").append(this.msgContext_font_color).append("\\\"}]]\",");
		
		//           "msg_id ":          56600006            ,
		bld.append("\"msg_id\":").append(this.msgId).append(",");
		//           "clientid ": "          68660513                ",
		bld.append("\"clientid\":\"").append(this.clientId).append("\",");
		//           "psessionid ": "8368046764001d636f6e6e7365727665725f77656271714031302e3133342e362e313338000076ce00001246036e0400d8e8885e6d0000000a40765735757a39446f4d6d00000028af926e1ece1fe6022dca52aa7125f4d7b5b0f7795c25aab78700cd93d65410088f7db7e04d3e07af"}
		bld.append("\"psessionid\":\"").append(this.psessionid).append("\"}");
		
		
		bld.append("&");
		//clientid:68660513
		bld.append("clientid=").append(this.clientId);
		bld.append("&");
		//psessionid:8368046764001d636f6e6e7365727665725f77656271714031302e3133342e362e313338000076ce00001246036e0400d8e8885e6d0000000a40765735757a39446f4d6d00000028af926e1ece1fe6022dca52aa7125f4d7b5b0f7795c25aab78700cd93d65410088f7db7e04d3e07af
		bld.append("psessionid=").append(this.psessionid);
		return bld.toString();
	}

	/**
	 * 通过Json串解析对象
	 * @param msgStr
	 * @return
	 */
	private static Send_buddy_msg2_RequestBody parseFromJsonStr(String msgStr) throws Exception{
		// TODO Auto-generated method stub
		if(StringUtils.isBlank(msgStr))
			return null;
		
		JsonFactory f = new JsonFactory();                                 
		 JsonParser jp = f.createJsonParser(msgStr);        
		 Send_buddy_msg2_RequestBody user = new Send_buddy_msg2_RequestBody();                                           
		 jp.nextToken(); // will return JsonToken.START_OBJECT (verify?)   
		 while (jp.nextToken() != JsonToken.END_OBJECT) {                  
		   String fieldname = jp.getCurrentName();                         
		   jp.nextToken(); // move to value, or START_OBJECT/START_ARRAY  
		   
		   if ("content".equals(fieldname)) { // contains an object    
			   //content的内容只能通过手工解析了
			   String contentStr = jp.getText();
			   parseContent(contentStr, user);
		                                              
		   } else if ("to".equals(fieldname)) {    
			   user.setTo(jp.getLongValue());
			   
		   } else if ("face".equals(fieldname)) {                      
		     user.setFace(jp.getIntValue());
		     
		   } else if ("msg_id".equals(fieldname)) {                     
		     user.setMsgId(jp.getIntValue());   
		     
		   }else if("clientid".equals(fieldname)){
			   user.setClientId(Integer.valueOf(jp.getText()));
		   }else if("psessionid".equals(fieldname)){
			   user.setPsessionid(jp.getText());
		   }else {                                                        
		     throw new IllegalStateException("Unrecognized field '" + fieldname);
		   }                                                               
		 }                                                                 
		 jp.close(); // ensure resources get cleaned up timely and properly
		
		return user;
	}



	private static void parseContent(String contentStr, Send_buddy_msg2_RequestBody sendMsg) {
		// TODO Auto-generated method stub
		   //["aaad",["font",{"name":"宋体","size":"10","style":[0,0,0],"color":"000000"}]]
//		   Pattern pattern = Pattern.compile("\\[\"([\\s\\S]*)\",\\[\"name\":\"([\\s\\S]*)\",\"size\":\"(\\d*)\",\"style\":\\[(\\d*),(\\d*),(\\d*)\\],\"color\":\"(\\d*)\"\\]\\]");
//		   Matcher matcher = pattern.matcher(contentStr);
//		   if(matcher.matches()) {
//			   String string = matcher.group(1);
//		   }
		if(StringUtils.isBlank(contentStr))
			return;
		
		//解析消息内容
		int idx = contentStr.indexOf("[\"");
		contentStr = contentStr.substring(idx + 1);
		idx = contentStr.indexOf("\",[\"font\"");
		String msg = contentStr.substring(1, idx);
		sendMsg.setMsgContext_data(msg);
		
		//解析消息内容对应的字体信息
		idx = contentStr.indexOf("{\"name");
		int last = contentStr.lastIndexOf("}");
		//{"name":"宋体","size":"10","style":[0,0,0],"color":"000000"}
		contentStr = contentStr.substring(idx, last + 1);
//		contentStr = replaceSpecialCharacter(contentStr);

		ObjectMapper map = new ObjectMapper();
		try {
			ContentFont font = map.readValue(contentStr, ContentFont.class);
			if(font != null) {
				sendMsg.setMsgContext_font_name(font.getName());
				sendMsg.setMsgContext_font_color(font.getColor());
				sendMsg.setMsgContext_font_size(font.getSize());
				sendMsg.setMsgContext_font_style(font.getStyle());
			}

		} catch (JsonParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JsonMappingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private static String replaceSpecialCharacter(String contentStr) {
		if(StringUtils.isBlank(contentStr))
			return "";
		
		//  {}[],.'":;~!@#$%^&*()_-+=|\?/
		contentStr = contentStr.replace("[", "【");
		contentStr = contentStr.replace("]", "】");
		contentStr.replace("", "");
		contentStr.replace("", "");
		contentStr.replace("", "");
		contentStr.replace("", "");
		
		
		return contentStr;
	}


	/**
	 * @param args
	 */
	public static void main(String[] args) throws Exception{
		// TODO Auto-generated method stub
//		String str = "r:{\"to\":953863072,\"face\":540,\"content\":\"[\"dda\",[\"font\",{\"name\":\"宋体\",\"size\":\"10\",\"style\":[0,0,0],\"color\":\"000000\"}]]\",\"msg_id\":74520001,\"clientid\":\"53452869\",\"psessionid\":\"8368046764001d636f6e6e7365727665725f77656271714031302e3133342e362e31333800001950000011e1036e0400d8e8885e6d0000000a403562426a684e7a484c6d00000028baab68f44cf83593dae2d761c9126c13eee48e210ec62313efc5b7dcce202dca1f64953d3069f004\"}&clientid:53452869&psessionid:8368046764001d636f6e6e7365727665725f77656271714031302e3133342e362e31333800001950000011e1036e0400d8e8885e6d0000000a403562426a684e7a484c6d00000028baab68f44cf83593dae2d761c9126c13eee48e210ec62313efc5b7dcce202dca1f64953d3069f004";
//		String str = "{\"to\":953863072,\"face\":540,\"content\":\"[\"abcde\",\"\\n【提示：此用户正在使用Q  Web：http://web.qq.com/】\",[\"font\",{\"name\":\"宋体\",\"size\":\"10\",\"style\":[0,0,0],\"color\":\"000000\"}]]\",\"msg_id\":74520001,\"clientid":"53452869","psessionid":"8368046764001d636f6e6e7365727665725f77656271714031302e3133342e362e31333800001950000011e1036e0400d8e8885e6d0000000a403562426a684e7a484c6d00000028baab68f44cf83593dae2d761c9126c13eee48e210ec62313efc5b7dcce202dca1f64953d3069f004"}";
		
//		parseFromRequestBody(str);
	}	
	
	
	public long getTo() {
		return to;
	}


	public void setTo(long to) {
		this.to = to;
	}


	public int getFace() {
		return face;
	}


	public void setFace(int face) {
		this.face = face;
	}


	public String getMsgContext_data() {
		return msgContext_data;
	}


	public void setMsgContext_data(String msgContext_data) {
		this.msgContext_data = msgContext_data;
	}


	public String getMsgContext_font_name() {
		return msgContext_font_name;
	}


	public void setMsgContext_font_name(String msgContext_font_name) {
		this.msgContext_font_name = msgContext_font_name;
	}


	public String getMsgContext_font_size() {
		return msgContext_font_size;
	}


	public void setMsgContext_font_size(String msgContext_font_size) {
		this.msgContext_font_size = msgContext_font_size;
	}


	public int[] getMsgContext_font_style() {
		return msgContext_font_style;
	}


	public void setMsgContext_font_style(int[] msgContext_font_style) {
		this.msgContext_font_style = msgContext_font_style;
	}


	public String getMsgContext_font_color() {
		return msgContext_font_color;
	}


	public void setMsgContext_font_color(String msgContext_font_color) {
		this.msgContext_font_color = msgContext_font_color;
	}


	public int getMsgId() {
		return msgId;
	}


	public void setMsgId(int msgId) {
		this.msgId = msgId;
	}


	public int getClientId() {
		return clientId;
	}


	public void setClientId(int clientId) {
		this.clientId = clientId;
	}


	public String getPsessionid() {
		return psessionid;
	}


	public void setPsessionid(String psessionid) {
		this.psessionid = psessionid;
	}



}
